//
//  ViewController.swift
//  ewgShop
//
//  Created by zzc on 2019/8/5.
//  Copyright © 2019 zzc. All rights reserved.
//

import UIKit
import Dispatch

@objcMembers class ViewController: ZZCCordovaBaseWebViewVC {

    var isPushing : Bool = false
    var referer : NSString?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    
    }

    override func viewWillAppear(_ animated: Bool) {
        print("viewWillAppear dssdf");
        super.viewWillAppear(animated);
    }
    
    override func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) -> Int {
        
        // 埋点业务逻辑
        
        
        // 拦截跳转App Store
        if (navigationAction.request.url != nil && navigationAction.request.url!.host != nil && (navigationAction.request.url!.host! as NSString).isEqual(to: "itunes.apple.com")) {
            return super.webView(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
        }
        
        // 处理重定向
        if (self.currentHref != nil &&  ((self.currentHref! as NSString).isEqual(to: "about:blank") &&
            (navigationAction.request.mainDocumentURL!.absoluteString as NSString).isEqual(to: navigationAction.request.url!.absoluteString)) == false) || ((webView.title == nil || webView.title?.lengthOfBytes(using: .utf8) == 0) && self.readyState == ZZCWKWebViewReadyState.Complete || self.redirectPage) {
            return WKNavigationActionPolicy.allow.rawValue
        }
        
        /**
         *
         */
        if self.readyState != ZZCWKWebViewReadyState.Complete || (self.readyState == ZZCWKWebViewReadyState.Interactive && (navigationAction.request.mainDocumentURL!.absoluteString as NSString).isEqual(to: navigationAction.request.url!.absoluteString)) == false || (self.readyState == ZZCWKWebViewReadyState.Complete && (navigationAction.request.url!.absoluteString as NSString).isEqual(to: self.startPage)){
            return super.webView(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
        }
        
        /**
         *  处理URL 跳转
         *  1. 非主frame为目标的请求
         *  2. reload
         */
        if (navigationAction.targetFrame != nil && navigationAction.targetFrame?.isMainFrame == false) || ( (navigationAction.request.url!.absoluteString as NSString).isEqual(to: self.currentHref ?? "")){
            return  super.webView(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
        }
        
        let url = navigationAction.request.url
        
        var requestAction = self.requestParseManager.actionForWebviewWithRequestAndNavigationType(webview: wkWebView, request: navigationAction.request as NSURLRequest, navigationType: navigationAction.navigationType);
        
        if url?.host?.contains("wx.tenpay") ?? false{
            return WKNavigationActionPolicy.allow.rawValue
        }
        
        // 处理 requestAction
        if requestAction == ZZCWebViewRequestAction.PushNewWebView {
            if self.isPushing {
                return WKNavigationActionPolicy.cancel.rawValue
            }
            self.isPushing = true
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
                self.isPushing = false
            }
            let vc  = self.createH5WebViewWithUrl(url: url?.absoluteString) as! ViewController
            
            let referer = (navigationAction.request.allHTTPHeaderFields! as NSDictionary).value(forKey: "Referer") as? NSString
            
            if referer != nil {
                vc.referer = referer
            }else{
                vc.referer = self.webViewEngine.url()?.absoluteString as NSString?
            }
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true);
            return WKNavigationActionPolicy.cancel.rawValue
        }
        
        
        if requestAction == ZZCWebViewRequestAction.OpenOtherApp && (url!.scheme! as NSString).isEqual(to: "openblack") {
            
        }
        
        
        return super.webView(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
    }
    
    override func webView(_ webView: WKWebView, decideResponsePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) -> Int {
        return super.webView(webView, decideResponsePolicyFor: navigationResponse, decisionHandler: decisionHandler)
    }
    
    override func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        super.webView(webView, didStartProvisionalNavigation: navigation)
    }
    
    override func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        super.webView(webView, didCommit: navigation)
    }
    
    override func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        super.webView(webView, didFinish: navigation)
    }
    
    override func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        super.webView(webView, didReceiveServerRedirectForProvisionalNavigation: navigation)
    }
    
    override func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        super.webView(webView, didFail: navigation, withError: error)
    }
    
    override func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        super.webView(webView, didFailProvisionalNavigation: navigation, withError: error)
    }
    
    override func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        super.webViewWebContentProcessDidTerminate(webView)
    }

//
//    @objc  func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
//        print("ViewConytoller webview decidePolicy")
//
////        let selector1 = #selector(webView(_:decidePolicyFor:decisionHandler:));
////        let selector2 =  NSSelectorFromString("webView:decidePolicyForNavigationAction:decisionHandler:");
////        if self.webViewEngine.responds(to: selector1) || self.webViewEngine.responds(to: selector2){
////            print("webEngine Can Response webview decidePolicy")
////
////            let webEngine = self.webViewEngine! as! WKNavigationDelegate;
////            webEngine.webView?(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
////
////        }else{
////            print("webEngine can not Resopnse webView decidePolicy")
////        }
//    }
    
    //MARK: Private
    func createH5WebViewWithUrl(url:String?) -> UIViewController {
        
        let vcWebViewController = ViewController()
        vcWebViewController.startPage = url
        return vcWebViewController;
    }

}

